package com.pateo.springcloudorder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.pateo.springcloudgoods.web.GoodsService;
import com.pateo.springcloudgoods.web.response.GoodsResponse;
import com.pateo.springcloudorder.dao.mapper.auto.AutoOrderMapper;
import com.pateo.springcloudorder.dao.model.auto.AutoOrder;
import com.pateo.springcloudorder.dao.model.auto.AutoOrderExample;
import com.pateo.springcloudorder.feignclient.GoodsFeignClient;
import com.pateo.springcloudorder.service.OrderService;
import com.pateo.springcloudorder.util.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AutoOrderMapper orderMapper;
    @Autowired
    private GoodsFeignClient goodsFeignClient;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;


    @Override
    public int insertOrder(AutoOrder order) {
        GoodsResponse goodsResponse = goodsFeignClient.queryGoods(order.getGoodsId());
        if(goodsResponse == null){
            throw new IllegalArgumentException("商品不存在");
        }
        order.setId(null);
        order.setOrderNumber(String.valueOf(new SnowflakeIdWorker(0,0).nextId()));
        order.setOrderStatus("0");
        order.setCreateTime(new Date());
        return orderMapper.insertSelective(order);
    }

    @Override
    public AutoOrder payOrder(String orderNumber) {
        AutoOrderExample example = new AutoOrderExample();
        example.createCriteria().andOrderNumberEqualTo(orderNumber);
        List<AutoOrder> orderList  = orderMapper.selectByExample(example);
        if(orderList.size() != 1){
            throw new IllegalArgumentException("订单编号错误");
        }
        AutoOrder order = orderList.get(0);
        order.setOrderStatus("1");
        order.setPayTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
        kafkaTemplate.send("order", JSONObject.toJSONString(order));
        return order;
    }
}
